﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;

namespace GoodStuff.SharePoint2007
{
    /// <summary>
    /// Baseclass for creating item (web,list,folder,item) picker
    /// </summary>
    public abstract class BaseBrowseItemToolpart<T> : Microsoft.SharePoint.WebPartPages.ToolPart where T : Microsoft.SharePoint.WebPartPages.WebPart
    {
        /// <summary>
        /// Creates a new BrowseItemToolpart which existing information about the item
        /// </summary>
        /// <param name="parentWebPart"></param>
        /// <param name="itemPath"></param>
        /// <param name="itemName"></param>
        public BaseBrowseItemToolpart(T parentWebPart, string itemPath, string itemName)
        {
            this.Configure(parentWebPart, itemPath, itemName);
        }

        /// <summary>
        /// Reference to the WebPart containing this Toolpart
        /// </summary>
        protected T WebPart { get; private set; }
        
        /// <summary>
        /// The Textbox that contains the path/url of the item
        /// </summary>
        protected TextBox txtItemPath = new TextBox();

        /// <summary>
        /// The Textbox that contains the name of the item
        /// </summary>
        protected TextBox txtItemName = new TextBox();

        /// <summary>
        /// The Button that can be pressed for saving
        /// </summary>
        protected Button butBrowse = new Button();

        /// <summary>
        /// Init function is called by the Webpart upon creation, initializing the Toolpart with its Webpart parent
        /// </summary>
        /// <param name="wp"></param>
        /// <param name="itemPath"></param>
        /// <param name="itemName"></param>
        private void Configure(T wp, string itemPath, string itemName)
        {
            this.WebPart = wp;
            txtItemPath.Text = itemPath;
            txtItemName.Text = itemName;
        }

        /// <summary>
        /// The text on the button
        /// </summary>
        public abstract string ButtonText { get; }

        /// <summary>
        /// The title to show on the toolpart
        /// </summary>
        public abstract string ToolpartTitle { get; }

        /// <summary>
        /// Function adds the desired controls on the page
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.Title = this.ToolpartTitle;
            txtItemPath.ID = "txtItemPath";
            txtItemName.ID = "txtItemName";
            butBrowse.ID = "butBrowse";
            butBrowse.Text = this.ButtonText;
            butBrowse.Attributes.Add("onClick", "LaunchSitePicker" + SPHttpUtility.EcmaScriptStringLiteralEncode(this.ID) + "(); return false;");

            this.Controls.Add(butBrowse);
            this.Controls.Add(txtItemPath);
            this.Controls.Add(txtItemName);
        }

        /// <summary>
        /// Inheriting class MUST implement applychanges to use the browse result
        /// </summary>
        public abstract override void ApplyChanges();

        /// <summary>
        /// Child class should specifiy which filter to use.
        /// </summary>
        public abstract BrowseItemToolpartFilter Filter { get; }

       /// <summary>
        // Override the OnPreRender to add custom javascript
       /// </summary>
       /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            Microsoft.SharePoint.WebControls.ScriptLink.Register(Page, "PickerTreeDialog.js", true);
            AddScript();

            base.OnPreRender(e);
        }

        /// <summary>
        /// Function adds a custom piece of javascript which will prefill our two textboxes using the standard Sharepoint Listviewer
        /// </summary>
        private void AddScript()
        {
            string scriptFormatString = @"
<script language='javascript'>
    var lastSelectedSiteSmtPickerId{2} = null;
    
    function LaunchSitePicker{2}(){{
        if (!document.getElementById) return; 
        var siteTextBox = document.getElementById('{0}');
        var siteListBox = document.getElementById('{1}');
        
        if (siteTextBox == null) return; 
        var serverUrl = '/'; 
        var callback=''; 
        var callback = 
            function(results){{
                if (results == null) return; 
                lastSelectedSiteSmtPickerId{2} = results[0];
                siteTextBox.value = '';
                siteListBox.value = '';
                siteTextBox.value = results[1]; 
                siteListBox.value = results[2];
            }};     
        
        LaunchPickerTreeDialog('CbqPickerSelectSiteTitle','CbqPickerSelectSiteText', '{3}','', serverUrl, lastSelectedSiteSmtPickerId{2},'','','/_layouts/images/smt_icon.gif','', callback);
    }}
</script>
";

            // format script
            scriptFormatString = string.Format(scriptFormatString, new object[]
            {
                    SPHttpUtility.EcmaScriptStringLiteralEncode(txtItemPath.ClientID), 
                    SPHttpUtility.EcmaScriptStringLiteralEncode(txtItemName.ClientID), 
                    SPHttpUtility.EcmaScriptStringLiteralEncode(this.ID), 
                    Filter
            });

            // add script to page 
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "LanchSitePicker" + this.ID, scriptFormatString);
        }
    }

    /// <summary>
    /// Filter of what to show in the listpicker
    /// </summary>
    public enum BrowseItemToolpartFilter
    {
        /// <summary>
        /// Pages only
        /// </summary>
        pages,

        /// <summary>
        /// Shows only webs
        /// </summary>
        websOnly,

        /// <summary>
        /// Shows only webs and lists
        /// </summary>
        websLists,

        /// <summary>
        /// Show webs, lists and folders
        /// </summary>
        websListsFolders
    }
}
